package ua.kiev.tosik.price.conf;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.database.connectors.ConnectorFactory;

import javax.swing.*;
import java.sql.Connection;

public class AdminLoaderWorker extends SwingWorker<Boolean, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.conf");
	private Connection conn;
	private Boolean status = true;

	public AdminLoaderWorker() {
		logger.debug("Starting config worker process");
	}

	@Override
	protected Boolean doInBackground() throws Exception {
		firePropertyChange("Message", null, "Load translations..");
		Language lang = Language.getInstance();
		if ( ! lang.isStatus() ) {
			firePropertyChange("Message", null, lang.getMessage());
			return false;
		}
		firePropertyChange("Message", null, "Loading skins..");
		SkinsConfig skinsConfig = SkinsConfig.getInstance();
		if ( skinsConfig.getSkinList().size() == 0 ) {
			firePropertyChange("Message", null, "Skins not found!");
			return false;
		}
		firePropertyChange("SkinAction", false, true);
		firePropertyChange("Message", null, "Connect to database " + AppConfig.getInstance().get("app.dbtype") + "..");
		ConnectorFactory connectorFactory = ConnectorFactory.getInstance(AppConfig.getInstance().get("app.dbtype"));
		Connection conn = connectorFactory.getConn();
		if ( conn == null ) {
			firePropertyChange("Message", null, connectorFactory.getErrorMessage());
			return false;
		}
		firePropertyChange("Message", null, "Applying default skin..");
		firePropertyChange("SwitchSkin", null, true);
		firePropertyChange("Message", null, "Load chapters..");
		ChapterConfig chapterConfig = ChapterConfig.getInstance();
		if ( chapterConfig.getChapterList().size() == 0 ) {
			firePropertyChange("Message", null, chapterConfig.getMessage());
			return false;
		}
		return true;
	}

	protected void done() {
		try {
			status = get();
			if ( status ) {
				// LoginDialog loginDialog = new LoginDialog();
				// firePropertyChange("Message", null, "Awaiting for authorization..");
				// loginDialog.open();
				logger.debug("Continue working");
			}
			firePropertyChange("Done", false, status);
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
